package com.cadre.common.utils.oldutil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/* loaded from: IPUtils.class */
public class IPUtils {
    private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            logger.error("IPUtils ERROR ", e);
        }
        return ip;
    }

    public static String getMACAddress(String ip) throws Exception {
        String macAddress = "";
        if ("127.0.0.1".equals(ip)) {
            byte[] mac = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    sb.append("-");
                }
                String s = Integer.toHexString(mac[i] & 255);
                sb.append(s.length() == 1 ? 0 + s : s);
            }
            return sb.toString().trim().toUpperCase();
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("nbtstat -A " + ip).getInputStream(), "GBK"));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                } else if (line != null) {
                    int index = line.indexOf("MAC Address = ");
                    if (index != -1) {
                        macAddress = line.substring(index + "MAC Address = ".length()).trim().toUpperCase();
                    } else {
                        int reindex = line.indexOf("MAC 地址 =");
                        if (reindex != -1) {
                            macAddress = line.substring(reindex + "MAC 地址 =".length()).trim().toUpperCase();
                        }
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }

    public static String getMac(String ip) throws IOException {
        String mac = null;
        if (ip != null) {
            try {
                LineNumberReader input = new LineNumberReader(new InputStreamReader(Runtime.getRuntime().exec("arp " + ip).getInputStream()));
                StringBuffer s = new StringBuffer();
                while (true) {
                    String line = input.readLine();
                    if (line == null) {
                        break;
                    }
                    s.append(line);
                }
                mac = s.toString();
                if (StringUtils.isNotBlank(mac)) {
                    mac = mac.substring(mac.indexOf(":") - 2, mac.lastIndexOf(":") + 3);
                }
                return mac;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mac;
    }

    public static String getMacInWindows(String ip) {
        return filterMacAddress(ip, callCmd(new String[]{"cmd", "/c", "ping " + ip}, new String[]{"cmd", "/c", "ipconfig -all"}), "-");
    }

    public static String callCmd(String[] cmd, String[] another) {
        String result = "";
        try {
            Runtime rt = Runtime.getRuntime();
            rt.exec(cmd).waitFor();
            BufferedReader br = new BufferedReader(new InputStreamReader(rt.exec(another).getInputStream(), "GBK"));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                result = result + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String filterMacAddress(String ip, String sourceString, String macSeparator) {
        String result = "";
        Matcher matcher = Pattern.compile("((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})").matcher(sourceString);
        while (matcher.find()) {
            result = matcher.group(1);
            int num = sourceString.indexOf(ip) - sourceString.indexOf(": " + result + " ");
            if (num > 0 && num < 300) {
                break;
            }
        }
        return result;
    }

    public static String getMacInfo(String ip) {
        try {
            String macAddr = getMac(ip);
            if (StringUtils.isBlank(macAddr)) {
                macAddr = getMacInWindows(ip).trim();
            }
            System.out.println("===========> login macaddress by ipconfig:" + macAddr);
            return macAddr;
        } catch (Exception e) {
            System.out.println("获取mac地址失败");
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println("===========> login macaddress:" + getMACAddress("127.0.0.1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        getMacInfo("192.168.137.12");
    }
}
